package com.wang.springframework.context.support;

import com.sun.istack.internal.Nullable;
import com.wang.springframework.beans.factory.FactoryBean;
import com.wang.springframework.beans.factory.InitializingBean;
import com.wang.springframework.core.convert.ConversionService;
import com.wang.springframework.core.convert.converter.Converter;
import com.wang.springframework.core.convert.converter.ConverterFactory;
import com.wang.springframework.core.convert.converter.ConverterRegistry;
import com.wang.springframework.core.convert.converter.GenericConverter;
import com.wang.springframework.core.convert.support.DefaultConversionService;
import com.wang.springframework.core.convert.support.GenericConversionService;

import java.util.Set;

/**
 * @author wangjianhua
 * @Description 提供创建 ConversionService工厂
 * 一个工厂，可方便地访问配置有适用于大多数环境的转换器的ConversionService。
 * 设置setConverters“converters”属性以补充默认转换器。
 * @date 2021/9/7/007 14:28
 **/
public class ConversionServiceFactoryBean implements FactoryBean<ConversionService>, InitializingBean {


    @Nullable
    private Set<?> converters;

    @Nullable
    private GenericConversionService conversionService;



    @Override
    public ConversionService getObject() throws Exception {
        return conversionService;
    }

    @Override
    public Class<?> getObjectType() {
        return conversionService.getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.conversionService = new DefaultConversionService();
        registerConverters(converters,conversionService);
    }

    private void registerConverters(Set<?> converters, ConverterRegistry registry){
        if(converters != null){
            for (Object converter : converters) {
                if(converter instanceof GenericConverter){
                    registry.addConverter((GenericConverter)converter);
                }
                else if(converter instanceof Converter<?,?>){
                    registry.addConverter((Converter<?,?>)converter);
                }
                else if(converter instanceof ConverterFactory<?,?>){
                    registry.addConverterFactory((ConverterFactory<?,?>)converter);
                }
                else {
                    throw new IllegalArgumentException("Each converter object must implement one of the" +
                            "Converter,ConverterFactory, or GenericConverter interfaces.");
                }
            }
        }
    }

    public void setConverters(Set<?> converters) {
        this.converters = converters;
    }
}
